package io.renren.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import io.renren.entity.FileManagerEntity;
import io.renren.entity.NationalFlagEntity;
import io.renren.service.FileManagerService;
import io.renren.service.NationalFlagService;
import io.renren.utils.annotation.IgnoreAuth;

@Controller
@RequestMapping("/f")
public class FController {
	
	@Autowired
	private FileManagerService fileManagerService;
	
	@Autowired
	private NationalFlagService nationalFlagService;

	@IgnoreAuth
	@GetMapping("/d/{url}")
	public void d(@PathVariable("url")String url, HttpServletResponse response) throws Exception {
		
		FileManagerEntity entity = fileManagerService.queryByUrl(url);
		NationalFlagEntity nationalFlag = nationalFlagService.queryByUrl(url);
		
		if(entity == null && nationalFlag == null) return;
		
		String filePath = null;
		if(entity != null) {
			filePath = entity.getFilePath();
		} else {
			filePath = nationalFlag.getFilePath();
		}
		
		File file = new File(filePath);
		
		response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        
        InputStream in = new FileInputStream(file); 

        ServletOutputStream out = response.getOutputStream();
        int len = 0;  
        byte[]buf = new byte[1024];  
        while((len = in.read(buf, 0, 1024)) != -1){  
        	out.write(buf, 0, len);
        } 
        
		out.flush();
	}
	
	@IgnoreAuth
	@GetMapping("/x/{url}")
	public void x(@PathVariable("url")String url, HttpServletResponse response) throws Exception {
		
		FileManagerEntity entity = fileManagerService.queryByUrl(url);
		if(entity == null) return;
		String filePath = entity.getFilePath();
		File file = new File(filePath);
		
		response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename="  
                + URLEncoder.encode(entity.getFileName(), "UTF-8"));  
        InputStream in = new FileInputStream(file); 

        ServletOutputStream out = response.getOutputStream();
        int len = 0;  
        byte[]buf = new byte[1024];  
        while((len = in.read(buf, 0, 1024)) != -1){  
        	out.write(buf, 0, len);
        } 
        
		out.flush();
	}
}
